import sys
import tkinter as tk
from tkinter import messagebox
import requests
from datetime import datetime

def upload_data(url, data):
    try:
        response = requests.post(url, json=data)
        if response.status_code == 201:  # 假设服务器返回201表示成功创建
            messagebox.showinfo("成功", "目标设置成功并已上传")
        else:
            messagebox.showerror("错误", f"服务器返回错误: {response.status_code} - {response.text}")
    except Exception as e:
        messagebox.showerror("错误", f"无法连接到服务器: {str(e)}")

def set_calorie_goal():
    calorie_goal = calorie_entry.get()
    if not calorie_goal:
        messagebox.showerror("错误", "请输入有效的卡路里目标")
        return
    
    current_time = datetime.now().strftime('%Y%m%d%H%M%S')
    concatenated_str = current_time + str(calorie_goal) + "86"  # 示例校验和计算，需根据实际情况调整
    check_sum = hash(concatenated_str) % 100  # 简单模拟校验和计算
    
    data_to_upload = {
        "data": {
            "time": current_time,
            "calorie_target": calorie_goal,
            "check_sum": str(check_sum)
        },
        "machine_id": machine_id
    }
    
    output_calories.config(text=f"卡路里目标: {calorie_goal}")
    upload_data("http://47.108.221.119:5000/setCalorieGoal", data_to_upload)

def set_distance_goal():
    distance_goal = distance_entry.get()
    if not distance_goal:
        messagebox.showerror("错误", "请输入有效的运动距离目标")
        return
    
    current_time = datetime.now().strftime('%Y%m%d%H%M%S')
    concatenated_str = current_time + str(distance_goal) + "88"  # 示例校验和计算，需根据实际情况调整
    check_sum = hash(concatenated_str) % 100  # 简单模拟校验和计算
    
    data_to_upload = {
        "data": {
            "time": current_time,
            "distance_target": distance_goal,
            "check_sum": str(check_sum)
        },
        "machine_id": machine_id
    }
    
    output_distance.config(text=f"运动距离目标: {distance_goal}")
    upload_data("http://47.108.221.119:5000/setDistanceGoal", data_to_upload)

machine_id = sys.argv[1] if len(sys.argv) > 1 else "未提供机器码"

root = tk.Tk()
root.title(f"设置目标 - 机器ID: {machine_id}")

# 卡路里目标部分
tk.Label(root, text="输入消耗卡路里目标").pack(pady=5)
calorie_entry = tk.Entry(root)
calorie_entry.pack(pady=5)

tk.Button(root, text="设置卡路里目标", command=set_calorie_goal).pack(pady=5)
output_calories = tk.Label(root, text="卡路里目标: 未设置")
output_calories.pack(pady=5)

# 运动距离目标部分
tk.Label(root, text="输入运动距离目标").pack(pady=5)
distance_entry = tk.Entry(root)
distance_entry.pack(pady=5)

tk.Button(root, text="设置运动距离目标", command=set_distance_goal).pack(pady=5)
output_distance = tk.Label(root, text="运动距离目标: 未设置")
output_distance.pack(pady=5)

root.mainloop()